package com.huawei.boss.xml;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * 实现xml和XmlElem元素对象里边的转换，使用dom来解析
 * @author c00170351
 *
 */
public abstract class DomXmltransStrategy implements XmltransStrategy {
    public List<XmlElem> xml2list(String xml) {
        ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
        return xml2list(is);
    }

    public List<XmlElem> xml2list(InputStream is) {
        Element root = readDoc(is);
        return parseRootNode(root);
    }

    /**
     * 关键方法，从xml转换成列表
     * @param root 待转换的报文根节点
     * @return 返回转换好的列表信息
     */
    public abstract List<XmlElem> parseRootNode(Element root);

    protected Element readDoc(InputStream is) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(is);
            return document.getDocumentElement();
        } catch (Exception e) {
            throw new RuntimeException("xml解析出错", e);
        }
    }

    public String list2xml(List<XmlElem> xmlElems, boolean isSort) {
        if (!isSort) {
            Collections.sort(xmlElems);
        }

        return list2xml(xmlElems);
    }
}
